//
//  UrbanLawEnForEndViewController.m
//  UrbanManagement
//
//  Created by Can on 2018/5/11.
//  Copyright © 2018年 hwd. All rights reserved.
//

#import "UrbanLawEnForEndViewController.h"
#import "UrbanPrinterViewController.h"
#import "UrbanMainViewController.h"
#import "UrbanBlueTooth.h"

@interface UrbanLawEnForEndViewController ()<CBCentralManagerDelegate>

@property (strong, nonatomic) UrbanBlueTooth *bluetooth;
@property (strong, nonatomic) CBPeripheral *peripheral;
@property (strong, nonatomic) NSMutableArray *listDevices;
@property (strong, nonatomic) CBCentralManager *centralManager;

@end

@implementation UrbanLawEnForEndViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initTitleWithTitle:@"执法完成"];
    
    self.listDevices = [NSMutableArray array];
    
    self.bluetooth = [[UrbanBlueTooth alloc]init];
    
    [self creatView];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.centralManager = [[CBCentralManager alloc]initWithDelegate:self queue:nil options:nil];
}

- (void)onTapLeftBarButton
{
    for (UIViewController *controller in self.navigationController.viewControllers){
        if ([controller isKindOfClass:[UrbanMainViewController class]]) {
            [self.navigationController popToViewController:controller animated:YES];
        }
    }
}

- (void)creatView
{
    UIImageView *imageView = [TomamaUI createImageView:CGRectMake((SCREENW - 304/2*screenW_6)/2, 174/2*screenW_6, 304/2*screenW_6, 249/2*screenW_6) backGroundImageV:@"icon05"];
    [self.view addSubview:imageView];
    
    UILabel *title = [TomamaUI createLabel:CGRectMake(0, CGRectGetMaxY(imageView.frame) + 23*screenW_6, SCREENW, 15*screenW_6) textAligment:1 font:[UIFont systemFontOfSize:15*screenW_6] textColor:[UIColor colorWithHexString:@"#666666"] text:@"违法记录提交成功!"];
    [self.view addSubview:title];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake((SCREENW - 255/2*screenW_6)/2, CGRectGetMaxY(title.frame) + 134/2*screenW_6, 255/2*screenW_6, 78/2*screenW_6);
    [button setTitle:@"打印罚单" forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:@"icon06"] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:15*screenW_6];
    [button addTarget:self action:@selector(printBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
}

- (void)printBtn
{
    for (int i = 0; i<_listDevices.count; i++) {
        NSString* uuid = [NSString stringWithFormat:@"%@", [[_listDevices objectAtIndex:i] identifier]];
        uuid = [uuid substringFromIndex:[uuid length] - 12];
        
        if ([[Storage getPrinter] isEqualToString:uuid]) {
            self.peripheral = [_listDevices objectAtIndex:i];
        }
    }
    [self print];
}

//开始查看服务, 蓝牙开启
- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
    switch (central.state) {
        case CBCentralManagerStatePoweredOn:
            [self BlueState];
            break;
            
        case CBManagerStatePoweredOff:
            [ToolViewVC addKeyAlterViewController:@"蓝牙未打开，请打开蓝牙" Controller:self];
            break;
            
        case CBManagerStateUnauthorized:
            [ToolViewVC addKeyAlterViewController:@"蓝牙未授权" Controller:self];
            break;
            
        case CBManagerStateUnsupported:
            [ToolViewVC addKeyAlterViewController:@"设备不支持蓝牙" Controller:self];
            break;
            
        case CBManagerStateResetting:
            [ToolViewVC addKeyAlterViewController:@"蓝牙重置状态" Controller:self];
            break;
            
        case CBManagerStateUnknown:
            [ToolViewVC addKeyAlterViewController:@"蓝牙处于未知状态" Controller:self];
            break;
            
        default:
            break;
    }
}

- (void)wrapPrintDatas
{
    [self.bluetooth StartPage:560 pageHeight:888 ];
    [self.bluetooth TextCenter:@"违法停车告知单" font:24 x:125 y:20];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"编    号:%@",_orderNumber] font:24 x:30 y:90];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"车辆牌号:%@",_plateNumber] font:24 x:30 y:130];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"车辆类型:%@",_carType] font:24 x:30 y:170];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"号牌颜色:%@",_numPlateColor] font:24 x:30 y:210];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"停放时间:%@",_parkTime] font:24 x:30 y:250];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"停放地点:%@",_address] font:24 x:30 y:290];
    [self.bluetooth TextLeft:@"   上述时间、地点，该机动车未在停车场或道路" font:24 x:30 y:350];
    [self.bluetooth TextLeft:@"停车泊位内停放，违反了《中华人民共和国道路安" font:24 x:30 y:390];
    [self.bluetooth TextLeft:@"全交通法》第56条的规定，违法行为已被拍照取证" font:24 x:30 y:430];
    [self.bluetooth TextLeft:@"。根据《湖北省实施<中华人民共和国道路交通安" font:24 x:30 y:470];
    [self.bluetooth TextLeft:@"全法>办法》第69条第十三项的规定，请自收到本" font:24 x:30 y:510];
    [self.bluetooth TextLeft:@"告知单5日内到西湖一路33号市城管执法局一楼服" font:24 x:30 y:550];
    [self.bluetooth TextLeft:@"务大厅接受处理。" font:24 x:30 y:590];
    [self.bluetooth TextLeft:[self getTimes] font:24 x:380 y:650];
    [self.bluetooth zp_darwQRCode:30 y:650 unit_width:4 text:@"https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzI2MTQ0MDA2Mg=="];
    [self.bluetooth TextLeft:@"关注“东坡城曦”" font:24 x:30 y:805];
    
    [self.bluetooth end];
}

- (void)wrapPrintJinGaoDatas
{
    [self.bluetooth StartPage:560 pageHeight:888 ];
    [self.bluetooth TextCenter:@"温 馨 提 示" font:24 x:125 y:20];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"编    号:%@",_orderNumber] font:24 x:30 y:90];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"车辆牌号:%@",_plateNumber] font:24 x:30 y:130];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"车辆类型:%@",_carType] font:24 x:30 y:170];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"号牌颜色:%@",_numPlateColor] font:24 x:30 y:210];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"停放时间:%@",_parkTime] font:24 x:30 y:250];
    [self.bluetooth TextLeft:[NSString stringWithFormat:@"停放地点:%@",_address] font:24 x:30 y:290];
    [self.bluetooth TextLeft:@"   上述时间、地点，该机动车未在停车场或道路" font:24 x:30 y:350];
    [self.bluetooth TextLeft:@"停车泊位内停放，请您看到提示后迅速将车辆转移" font:24 x:30 y:390];
    [self.bluetooth TextLeft:@"到规定地点停放。" font:24 x:30 y:430];
    [self.bluetooth TextLeft:@"   节日期间，为了您有一个愉快的心情，本次不" font:24 x:30 y:470];
    [self.bluetooth TextLeft:@"予处罚，如再次违停将依法处罚，请您理解，支持" font:24 x:30 y:510];
    [self.bluetooth TextLeft:@"和配合，祝您快乐！" font:24 x:30 y:550];
    [self.bluetooth TextLeft:[self getTimes] font:24 x:380 y:610];
    [self.bluetooth zp_darwQRCode:30 y:610 unit_width:4 text:@"https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzI2MTQ0MDA2Mg=="];
    [self.bluetooth TextLeft:@"关注“东坡城曦”" font:24 x:30 y:765];
    
    [self.bluetooth end];
}

- (NSString *)getTimes
{
    // 日期格式化类
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    // 设置日期格式(为了转换成功)
    fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    
    // NSString * -> NSDate *
    NSDate *date = [fmt dateFromString:_parkTime];
    
    // 利用NSCalendar处理日期
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *cmps = [calendar components:unit  fromDate:date];
    
    NSString *time = [NSString stringWithFormat:@"%ld年%ld月%ld日",(long)cmps.year,(long)cmps.month,(long)cmps.day];
    
    return time;
}

- (void)print{
    
    /* Byte byte[] = {0x0d,0x0a};
     NSData *adata = [[NSData alloc] initWithBytes:byte length:2];
     [self.bluetooth open:self.peripheral];
     [self.bluetooth flushRead];
     [self.bluetooth writeData:adata];
     [self.bluetooth close];
     */
    if (self.peripheral) {
        [self.bluetooth open:self.peripheral];
        [self.bluetooth flushRead];
        
        if ([_flag integerValue] == 3) {
            [self wrapPrintJinGaoDatas];
        }else{
            
            [self wrapPrintDatas];
        }
        [self sendPrintData];
        [self.bluetooth reset];
        [self.bluetooth close];
        
        [self onTapLeftBarButton];
    }else{
        UrbanPrinterViewController *printer = [UrbanPrinterViewController new];
        printer.orderNumber = _orderNumber;
        printer.plateNumber = _plateNumber;
        printer.carType = _carType;
        printer.numPlateColor = _numPlateColor;
        printer.parkTime = _parkTime;
        printer.address = _address;
        printer.flag = _flag;
        [self.navigationController pushViewController:printer animated:YES];
    }
}

-(void)sendPrintData{
    
    int r = self.bluetooth.dataLength;
    
    NSData *data = [self.bluetooth getData:r];
    
    [self.bluetooth writeData:data];
}

- (void)BlueState
{
    if(_listDevices != nil){
        _listDevices = nil;
        _listDevices = [NSMutableArray array];
    }
    
    BLOCK_CALLBACK_SCAN_FIND callback =
    ^( CBPeripheral*peripheral)
    {
        [self.listDevices addObject:peripheral];
        NSLog(@"scan find: %@",self.listDevices );
        
        NSMutableArray *listAry = [[NSMutableArray alloc]init];
        for (NSString *str in self.listDevices) {
            if (![listAry containsObject:str]) {
                [listAry addObject:str];
            }
        }
        
        for (int i = 0; i < listAry.count; i++) {
            if (![[listAry objectAtIndex:i] name]) {
                [listAry removeObjectAtIndex:i];
            }
        }
        
        self.listDevices = listAry;
    };
    
    [self.bluetooth scanStart:callback];
    
    double delayInSeconds = 5.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds* NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [self.bluetooth scanStop];
    });
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
